import config from '~/config'

import IPairTxData from '~/models/IData'
import IPlugin from './IPlugin'

import SwapNamePlugin from './SwapNamePlugin'
import SwapColPlugin from './SwapColPlugin'
import AccountPlugin from './AccountPlugin'
import WhiteListPlugin from './WhiteListPlugin'
import TimeDisplayPlugin from './TimeDisplayPlugin'
import IsContractPlugin from './IsContractPlugin'
import SellAccountAdjustPlugin from './SellAccountAdjustPlugin'

let firstBuild = true;
export default class DataBuilder {

    data: IPairTxData
    pluginList: IPlugin[]

    constructor(data: IPairTxData) {
        // console.log(data)
        this.data = data;
        this.pluginList = [];
    }

    useConfigPluginList() {
        return this
            .useIf(new SwapNamePlugin, config.plugins.SwapNamePlugin)
            .useIf(new SwapColPlugin, config.plugins.SwapColPlugin)
            .useIf(new AccountPlugin, config.plugins.AccountPlugin)
            .useIf(new SellAccountAdjustPlugin, config.plugins.SellAccountAdjustPlugin)
            .useIf(new WhiteListPlugin, config.plugins.WhiteListPlugin)
            .useIf(new TimeDisplayPlugin, config.plugins.TimeDisplayPlugin)
            .useIf(new IsContractPlugin, config.plugins.IsContractPlugin)
    }

    use(plugin: IPlugin) {
        this.pluginList.push(plugin)
        return this;
    }

    useIf(plugin: IPlugin, status: boolean) {
        if (status) {
            this.pluginList.push(plugin)
        }
        return this;
    }

    async build() {
        if (!this.data) {
            console.warn('falsy data')
            console.warn(this.data)
            return this.data
        }
        this.data.plugins = []
        if (firstBuild) {
            console.log('## Active Plugins')
        }
        for (const plugin of this.pluginList) {
            try {
                this.data = await plugin.modData(this.data) as IPairTxData
            }
            catch(err) {
                console.error(`error occured: ${plugin.name}`)
                console.error(err)
            }
            (this.data.plugins as string[]).push(plugin.name)
            if (firstBuild) {
                console.log(`- %c${plugin.name}`, 'color: #0043ff')
            }
            
        }
        firstBuild = false;
        return this.data;
    }
}


